package com.loong.game2048.server.impl;

import com.loong.game2048.Exception.BizException;
import com.loong.game2048.Exception.BizExceptionCodeEnum;
import com.loong.game2048.dao.CommentDao;
import com.loong.game2048.dao.UserDao;
import com.loong.game2048.module.Comment;
import com.loong.game2048.module.ResultCode;
import com.loong.game2048.module.User;
import com.loong.game2048.module.vo.CommentVo;
import com.loong.game2048.module.vo.Result;
import com.loong.game2048.server.CommentServer;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class CommentServerImpl implements CommentServer {

    @Resource
    private CommentDao commentDao;
    @Resource
    private UserDao userDao;

    @Override
    public Result pubComment(Comment comment) {
        comment.setTime(new Date());
        commentDao.addComment(comment);
        Result result = new Result();
        result.setCode(ResultCode.SUCCESS);
        result.setMsg("评论成功");
        return result;
    }

    @Override
    public List<CommentVo> findByParentId(Integer id) {

        //查找评论
        List<Comment> comments = commentDao.findByParentId(id);
        List<CommentVo> commentVos = new ArrayList<>();
        for (Comment comment : comments) {
            CommentVo commentVo = new CommentVo();
            BeanUtils.copyProperties(comment, commentVo);
            User user = userDao.getUserById(comment.getUId());
            commentVo.setUser(user);
            commentVos.add(commentVo);
        }
        return commentVos;
    }


    @Override
    public Result reply(Comment comment) {

        //获取被回复人的信息
        Integer id = comment.getParentId();
        Comment dbComment = commentDao.findById(id);
        if (dbComment == null){
            throw new BizException(BizExceptionCodeEnum.FORUM_NOT_FOUND);
        }
        String uId = dbComment.getUId();
        User userById = userDao.getUserById(uId);
        if (userById == null){
            throw new BizException(BizExceptionCodeEnum.SPECIFIED);
        }
        //设置被回复者姓名
        comment.setReplier(userById.getNickname());

        //回复的是二级评论，就修改父ID
        if (dbComment.getType() == 2){
            System.out.println("回复二级");
            comment.setParentId(dbComment.getParentId());
        }
        comment.setTime(new Date());

        //插入数据库
        commentDao.reply(comment);
        Result result = new Result();
        result.setCode(ResultCode.SUCCESS);
        result.setMsg("回复成功");
        return result;
    }

}
